package com.merchant.home;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.merchant.constant.Constants;
import com.merchant.json.ReadJson;
import com.merchant.util.AsycImageLoader;
import com.merchant.util.LoadingDialog;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.merchant.activity.R;
import com.zjxfood.merchant.activity.wxapi.WXEntryActivity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class BussnessTakeMoneyActivity extends Activity implements
		OnClickListener {
	private ImageView take_money_back;
	private RelativeLayout main_take_money;
	private ImageButton modify_bank_card;
	private ImageButton set_password_bank_card;
	private ArrayList<HashMap<String, Object>> mMap;
	private HashMap<String, Object> mUserMapLists;
	private HashMap<String, Object> UserMapLists;
	private ArrayList<HashMap<String, Object>> mDataList;
	private ArrayList<HashMap<String, Object>> getbankDataList;
	private EditText user_takemoney_edit;
	private EditText user_name_edit;
	private EditText user_phone_edit;
	// private EditText user_cardid_edit;
	private EditText user_takemoney_psaaword_edit;
	private EditText take_yzm;
	private Button btn_ttakemoney_submit;
	private TextView home_take_money;
	String money2 = null;
	String code1 = null;
	private LinearLayout forget_password_ll;
	private TextView take_money_text;
	private String phone = "15928046246";
	private String code;
	private int n = 60;
	private Timer mTimer;
	private boolean isClick = true;
	private TextView take_code;
	private TextView take_pwd;
	private FrameLayout user_frame_layout;
	private FrameLayout user_frame_layout1;
	// private FrameLayout user_frame_layout3;
	private PopupWindow pop_window; // PopupWindow对象声明
	private TextView mWebView;
	private TextView btn_cancel;
	private PopupWindow popupW = null;
	private ImageView weixin_login_ig;
	private TextView weixin_login_text;
	public static IWXAPI api;
	public static boolean isWXLogin = false;
	private AsycImageLoader imageloader;
	private Bitmap bitmap = null;// 图片对象
	private int num = 0;
	private LoadingDialog dialog;
	private TextView tixian_gz;// 提现规则

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_merchant_take_money);
		Intent intent = getIntent();
		money2 = intent.getStringExtra("money2");
		// code1 = intent.getStringExtra("code");
		init();
		// new Thread(getbank).start();
		regToWx();
		// if (isWXLogin) {
		// }
		registerBoradcastReceiver();
	}

	private void init() {
		main_take_money = (RelativeLayout) findViewById(R.id.main_take_money);
		take_money_back = (ImageView) main_take_money
				.findViewById(R.id.takemoney_back_image);
		// modify_bank_card = (ImageButton)
		// findViewById(R.id.modify_bank_card_ib);
		set_password_bank_card = (ImageButton) findViewById(R.id.set_password_bank_card);
		user_takemoney_edit = (EditText) findViewById(R.id.user_takemoney_edit);
		user_name_edit = (EditText) findViewById(R.id.user_name_edt);
		user_phone_edit = (EditText) findViewById(R.id.user_phone_edt);
		// user_cardid_edit = (EditText) findViewById(R.id.user_cardid_edit);
		user_takemoney_psaaword_edit = (EditText) findViewById(R.id.user_takemoney_password);
		btn_ttakemoney_submit = (Button) findViewById(R.id.user_takemoney_submit);
		home_take_money = (TextView) findViewById(R.id.take_money);
		forget_password_ll = (LinearLayout) findViewById(R.id.forget_password_ll);
		take_money_text = (TextView) findViewById(R.id.take_money_text);
		take_yzm = (EditText) findViewById(R.id.take_yzm);
		take_pwd = (TextView) findViewById(R.id.take_pwd);
		take_code = (TextView) findViewById(R.id.take_code);
		user_frame_layout = (FrameLayout) findViewById(R.id.username_frame_layout);
		user_frame_layout1 = (FrameLayout) findViewById(R.id.username_frame_layout1);
		// user_frame_layout3 = (FrameLayout)
		// findViewById(R.id.username_frame_layout3);
		weixin_login_ig = (ImageView) findViewById(R.id.weixin_login_ig);
		weixin_login_text = (TextView) findViewById(R.id.weixin_login_text);
		tixian_gz = (TextView) findViewById(R.id.tixian_gz);
		user_name_edit.setOnClickListener(this);
		user_frame_layout.setOnClickListener(this);
		user_frame_layout1.setOnClickListener(this);
		// user_frame_layout3.setOnClickListener(this);
		take_code.setOnClickListener(this);
		if (Constants.mtype != null) {
			if (Constants.mtype.equals("3")) {
				take_money_text.setText("营业收入提现");
			} else {
				take_money_text.setText("用户收益提现");
			}
		}
		home_take_money.setText("¥" + money2);
		user_takemoney_edit.setText(money2);
		btn_ttakemoney_submit.setOnClickListener(this);
		// modify_bank_card.setOnClickListener(this);
		take_money_back.setOnClickListener(this);
		set_password_bank_card.setOnClickListener(this);
		forget_password_ll.setOnClickListener(this);
		user_name_edit.setOnClickListener(this);
		user_phone_edit.setOnClickListener(this);
		weixin_login_ig.setOnClickListener(this);
		// user_cardid_edit.setOnClickListener(this);
		tixian_gz.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.take_code:
			// if (!(mPhoneEdit.getText().toString().equals(""))) {
			if (user_takemoney_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请先输入您想提取的金额！", 0).show();
			} else if (user_name_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请先输入真实姓名！", 0).show();

			} else if (user_phone_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请先输入联系电话！", 0).show();

			} else if (user_takemoney_psaaword_edit.getText().toString()
					.equals("")) {
				Toast.makeText(this, "请先输入提现密码！", 0).show();
			} else if (isClick) {
				take_code.setTextColor(getResources().getColor(R.color.no));
				isClick = false;
				Random random = new Random();
				String result = "";
				for (int i = 0; i < 6; i++) {
					result += random.nextInt(10);
				}
				code = result;
				Log.i("test", code + "==========code=========");
				mTimer = new Timer();
				TimerTask task = new TimerTask() {
					public void run() {
						n--;
						if (n <= 0) {
							handler.sendEmptyMessageDelayed(6, 0);
						} else {
							handler.sendEmptyMessageDelayed(5, 0);
						}
					}
				};
				mTimer.schedule(task, 60, 1000);
				dialog = new LoadingDialog(this, "发送中......");
				dialog.show();
				new Thread(codeRun).start();
			}
			// Toast.makeText(getApplicationContext(), "手机号不能为空!",
			// Toast.LENGTH_SHORT).show();
			//
			// }
			Log.i("gallery", code + "=======================");
			break;
		case R.id.takemoney_back_image:
			finish();
			break;
		case R.id.weixin_login_ig:
			// isWXLogin = true;
			WXEntryActivity.cc = "1";
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "wechat_sdk_demo_test";
			api.sendReq(req);
			if (api.sendReq(req) == false) {
				Toast.makeText(getApplicationContext(), "请先下载微信!",
						Toast.LENGTH_SHORT);
			}
			Log.i("msg", " " + api.sendReq(req));
			break;
		case R.id.forget_password_ll:
			intent.setClass(getApplicationContext(), SetPassWordActivity.class);
			startActivity(intent);
			break;
		case R.id.set_password_bank_card:
			intent.setClass(getApplicationContext(), SetPassWordActivity.class);
			startActivity(intent);
			break;
		case R.id.user_takemoney_submit:
			if (user_takemoney_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请输入您想提取的金额！", 0).show();
			} else if (user_name_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请输入真实姓名！", 0).show();

			} else if (user_phone_edit.getText().toString().equals("")) {
				Toast.makeText(this, "请输入联系电话！", 0).show();

			} else if (user_takemoney_psaaword_edit.getText().toString()
					.equals("")) {
				Toast.makeText(this, "请输入提现密码！", 0).show();
			} else if (take_yzm.getText().toString().equals("")) {
				Toast.makeText(getApplicationContext(), "请输入手机验证码！",
						Toast.LENGTH_SHORT).show();
			} else if (!take_yzm.getText().toString().equals(code)) {
				Toast.makeText(getApplicationContext(), "验证码输入错误！",
						Toast.LENGTH_SHORT).show();
			} else if (Constants.openid != null && Constants.nickname != null) {
				// Toast.makeText(this, "提现密码错误，请仔细核对！", 0).show();
				dialog = new LoadingDialog(this, "提取中......");
				dialog.show();
				new Thread(moneyout).start();
			} else {
				Toast.makeText(getApplicationContext(), "请先登录微信！",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.tixian_gz:
			intent.setClass(getApplicationContext(), TiXianGZActivity.class);
			startActivity(intent);
			break;

		}
	}

	private void regToWx() {
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
		api.registerApp(Constants.APP_ID);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			code1 = intent.getExtras().get("code").toString();
			Constants.code = intent.getExtras().get("code").toString();
			Log.i("code", Constants.code);
			new Thread(gettoken).start();
		}
	};

	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(WXEntryActivity.ACTION_NAME);
		// 注册广播
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	// 注销广播
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	// 根据code得到access_token、openid
	Runnable gettoken = new Runnable() {
		@Override
		public void run() {
			try {
				String strr = Constants.gettoken + "appid=" + Constants.APP_ID
						+ "&secret=" + Constants.AppSecret + "&code="
						+ Constants.code + "&grant_type=authorization_code";
				String json = ReadJson.readParse(strr);
				// Log.i("mUserMapLists", "================" + json);
				mUserMapLists = Constants.getJson2Object(json);
				Log.i("WX",
						"================"
								+ mUserMapLists.get("access_token").toString());
				Constants.access_token = mUserMapLists.get("access_token")
						.toString();
				Constants.openid = mUserMapLists.get("openid").toString();
				Log.i("WX_CODE", "================" + mUserMapLists);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.sendEmptyMessageDelayed(9, 0);
		}
	};
	// 根据access_token、openid得到用户信息
	Runnable userinfo = new Runnable() {
		@Override
		public void run() {
			try {
				String strr = Constants.userinfo + "access_token="
						+ Constants.access_token + "&openid="
						+ Constants.openid;
				String json = ReadJson.readParse(strr);
				// Log.i("mUserMapLists", "================" + json);
				UserMapLists = Constants.getJson2Object(json);
				Log.i("userinfo", "================" + UserMapLists);
				Constants.nickname = UserMapLists.get("nickname").toString();
				handler.sendEmptyMessageDelayed(8, 0);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	// 提现
	Runnable moneyout = new Runnable() {
		@Override
		public void run() {
			try {
				if (Constants.mtype != null) {
					if (Constants.mtype.equals("3")) {
						num = 1;
					} else {
						num = 0;
					}
				}
				String ss = "userId=" + Constants.Id + "&money="
						+ user_takemoney_edit.getText().toString()
						+ "&payPass="
						+ user_takemoney_psaaword_edit.getText().toString()
						+ "&realName=" + user_name_edit.getText().toString()
						+ "&mobile=" + user_phone_edit.getText().toString()
						+ "&wxNickName=" + Constants.nickname + "&wxOpenId="
						+ Constants.openid + "&vCode=" + code;
				String sign = Constants.sortsStr(ss);
				String strr = Constants.BusinessMoneyWithdrawals
						+ sign
						+ "&userId="
						+ Constants.Id
						+ "&money="
						+ user_takemoney_edit.getText().toString()
						+ "&payPass="
						+ user_takemoney_psaaword_edit.getText().toString()
						+ "&realName="
						+ URLEncoder.encode(
								user_name_edit.getText().toString(), "UTF-8")
						+ "&mobile=" + user_phone_edit.getText().toString()
						+ "&wxNickName="
						+ URLEncoder.encode(Constants.nickname, "UTF-8")
						+ "&wxOpenId=" + Constants.openid + "&vCode=" + code;
				String json = ReadJson.readParse(strr);
				mUserMapLists = Constants.getJson2Object(json);
				mDataList = Constants.getJsonArray(mUserMapLists.get("Data")
						.toString());
				Log.i("mMap", "================" + mUserMapLists);
				dialog.dismiss();
				if (mUserMapLists != null && mUserMapLists.size() > 0) {
					handler.sendEmptyMessageDelayed(3, 0);
				}
				// handler.sendEmptyMessageDelayed(1, 0);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				dialog.dismiss();
				handler.sendEmptyMessageDelayed(10, 0);
				e.printStackTrace();
			}
		}
	};

	Runnable getbank = new Runnable() {
		@Override
		public void run() {
			try {
				String ss = "uid=" + Constants.Id;
				String sign = Constants.sortsStr(ss);
				String strr = Constants.getbank + sign + "&uid=" + Constants.Id;
				String json = ReadJson.readParse(strr);
				mUserMapLists = Constants.getJson2Object(json);
				getbankDataList = Constants.getJsonArray(mUserMapLists.get(
						"Data").toString());
				// Log.i("mDataList", "================" + mDataList);
				handler.sendEmptyMessageDelayed(2, 0);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	Runnable codeRun = new Runnable() {
		@Override
		public void run() {
			try {
				// URLEncoder.encode("很满意", "UTF_8")
				// String content = URLEncoder.encode("【中佳信集团】", "UTF_8")
				// + URLEncoder.encode(code, "UTF_8")
				// + URLEncoder
				// .encode("（食尚男女(商家版)手机验证码，10分钟内有效）", "UTF_8");
				String ss = "mobile=" + Constants.mobile + "&Code=" + code;
				String sign = Constants.sortsStr(ss);
				String str = Constants.getSmsMsg + sign + "&mobile="
						+ Constants.mobile + "&Code=" + code;
				String json = ReadJson.readParse(str);
				mUserMapLists = Constants.getJson2Object(json);
				Log.i("Constants.mobile", Constants.mobile
						+ "=====================");
				handler.sendEmptyMessageDelayed(4, 0);
				dialog.dismiss();
				if (mUserMapLists != null && mUserMapLists.size() > 0) {
					handler.sendEmptyMessageDelayed(7, 0);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				dialog.dismiss();
				handler.sendEmptyMessageDelayed(10, 0);
				e.printStackTrace();
			}
		}
	};

	@SuppressLint("ClickableViewAccessibility")
	Handler handler = new Handler() {
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@SuppressLint({ "InlinedApi", "ClickableViewAccessibility" })
		public void handleMessage(Message msg) {
			imageloader = new AsycImageLoader();
			switch (msg.what) {
			case 1:

				break;
			case 2:
				if (getbankDataList.get(0).get("personname") != null) {
					user_name_edit.setText(getbankDataList.get(0)
							.get("personname").toString());
				} else {
					user_name_edit.setText("");
				}
				if (getbankDataList.get(0).get("mobile") != null) {
					user_phone_edit.setText(getbankDataList.get(0)
							.get("mobile").toString());
				} else {
					user_phone_edit.setText("");
				}
				break;
			case 3:
				LayoutInflater inflater1 = LayoutInflater
						.from(getApplicationContext());
				View view1 = inflater1.inflate(R.layout.pop_merchant_successd,
						null);
				mWebView = (TextView) view1.findViewById(R.id.notice_popup);
				btn_cancel = (TextView) view1
						.findViewById(R.id.popup_cancel_text);
				popupW = new PopupWindow(view1, LayoutParams.MATCH_PARENT,
						LayoutParams.WRAP_CONTENT, false);
				popupW.setBackgroundDrawable(new ColorDrawable(-00000000));// 设置背景透明
				popupW.setFocusable(true);// 获得焦点
				popupW.setOutsideTouchable(true);// 设置点击窗口外，popupWindow消失
				popupW.setAnimationStyle(R.style.AnimTop);
				popupW.showAtLocation(user_phone_edit, Gravity.CENTER, 0, 0);
				popupW.update();// 刷新内容
				view1.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (popupW != null && popupW.isShowing()) {
							popupW.dismiss();
							popupW = null;
						}
						return false;
					}
				});
				if (mUserMapLists.get("Message") != null) {
					mWebView.setText(mUserMapLists.get("Message").toString());
				}
				btn_cancel.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						popupW.dismiss();
					}
				});
				// Toast.makeText(getApplicationContext(),
				// mMap.get(1).get("Message").toString(), 0).show();
				break;
			case 4:
				take_code.setTextColor(getResources().getColor(R.color.no));
				isClick = false;
				break;
			case 5:
				take_pwd.setText(n + "");
				take_pwd.setVisibility(View.VISIBLE);

				break;
			case 6:
				take_code.setTextColor(getResources().getColor(R.color.white));
				mTimer.cancel();
				mTimer.purge();
				mTimer = null;
				isClick = true;
				n = 60;
				take_pwd.setVisibility(View.GONE);
				break;
			case 7:
				LayoutInflater inflater = LayoutInflater
						.from(getApplicationContext());
				View view = inflater.inflate(R.layout.pop_merchant_successd,
						null);
				mWebView = (TextView) view.findViewById(R.id.notice_popup);
				btn_cancel = (TextView) view
						.findViewById(R.id.popup_cancel_text);
				popupW = new PopupWindow(view, LayoutParams.MATCH_PARENT,
						LayoutParams.WRAP_CONTENT, false);
				popupW.setBackgroundDrawable(new ColorDrawable(-00000000));// 设置背景透明
				popupW.setFocusable(true);// 获得焦点
				popupW.setOutsideTouchable(true);// 设置点击窗口外，popupWindow消失
				popupW.setAnimationStyle(R.style.AnimTop);
				popupW.showAtLocation(user_phone_edit, Gravity.CENTER, 0, 0);
				popupW.update();// 刷新内容
				view.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (popupW != null && popupW.isShowing()) {
							popupW.dismiss();
							popupW = null;
						}
						return false;
					}
				});
				if (mUserMapLists.get("Message") != null) {
					mWebView.setText(mUserMapLists.get("Message").toString());
				}
				btn_cancel.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						popupW.dismiss();
					}
				});
				// Toast.makeText(getApplicationContext(),
				// mMap.get(1).get("Message").toString(), 0).show();
				break;
			case 8:
				if (UserMapLists.get("nickname") != null) {
					weixin_login_text.setText(UserMapLists.get("nickname")
							.toString());
				}

				if (UserMapLists.get("headimgurl") != null) {
					bitmap = imageloader.showImageAsyn(weixin_login_ig,
							UserMapLists.get("headimgurl").toString(),
							R.drawable.weixin_photo1);
					weixin_login_ig.setImageBitmap(bitmap);
				}

				break;
			case 9:
				new Thread(userinfo).start();
				break;
			case 10:
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
}
